#include <Editor/StdAfx.h>
#include "ResourceTree.h"
#include "GameToolApp.h"
#include "../GameLib/EngineFacade.h"

#include <wx/dnd.h>
#include <assert.h>

BEGIN_EVENT_TABLE(ResourceTree, wxTreeCtrl)
		EVT_TREE_BEGIN_DRAG(wxID_ANY, OnBeginDrag)
END_EVENT_TABLE()

ResourceTree::ResourceTree(wxWindow* parent)
	: wxTreeCtrl(parent)
{
	mRoot = AddRoot(_("Resources"));
	
	mEffectsItem = AppendItem(mRoot, _("Effects"));
	mRigidMeshItem = AppendItem(mRoot, _("RigidMeshes"));
	mSkinnedMeshItem = AppendItem(mRoot, _("SkinnedMeshes"));

	Expand(mRoot);
}


ResourceTree::~ResourceTree(void)
{
}

void ResourceTree::RefreshParticleSystemTree()
{
	// Query Particle System Template list to the Engine Facade
	std::vector<std::string> templateList; // this is not that safe but good to avoid dependencies.
											// should use same compilation options.
	EngineFacade::QueryParticleSystemTemplateList(templateList);

	// Add items per particle system template
	assert(mEffectsItem.IsOk());
	unsigned size = templateList.size();
	for(unsigned i=0; i<size; i++)
	{
		AppendItem(mEffectsItem, wxString::FromAscii(templateList[i].c_str()));
	}
}

void ResourceTree::RefreshMeshTree()
{
	// Query mesh list to the Engine Facade
	std::vector<std::string> meshList; // this is not that safe but good to avoid dependencies.
										// should use same compilation options.
	EngineFacade::QueryMeshList(meshList);

	// Add items per mesh
	assert(mRigidMeshItem);
	unsigned size = meshList.size();
	for (unsigned i=0; i<size; i++)
	{
		AppendItem(mRigidMeshItem, wxString::FromAscii(meshList[i].c_str()));
	}
}

void ResourceTree::OnBeginDrag(wxTreeEvent& e)
{
	wxTreeItemId item = e.GetItem();
	if (item == mRoot || item == mEffectsItem || item == mRigidMeshItem || item == mSkinnedMeshItem)
	{
		return;
	}
	wxString category = GetCategoryString(item);
	assert(!category.empty());
	wxString text = category + wxT("\t") + GetItemText(item);
	wxTextDataObject textData(text);
	wxDropSource source( textData, this, wxDROP_ICON(dnd_copy), wxDROP_ICON(dnd_move), wxDROP_ICON(dnd_none) );
	int flags = wxDrag_CopyOnly;
	wxDragResult result = source.DoDragDrop(flags);

}

wxString ResourceTree::GetCategoryString(const wxTreeItemId& item) const
{
	wxArrayString strParents;
	wxTreeItemId parent = GetItemParent(item);
	while (parent.IsOk())
	{
		strParents.push_back(GetItemText(parent));
		parent = GetItemParent(parent);
	}
	unsigned size = strParents.size();
	if (size >= 2)
	{
		return strParents[size-2];
	}
	else
	{
		return wxString();
	}

}